<!--自评计划添加框-->
<template>
  <el-dialog
      v-model="visible"
      v-bind="$attrs"
      :close-on-click-modal="false"
      draggable
      @closed="closed()"
  >
    <template #header>
      <div class="dialog-title">{{ $t('menuStr.ifaceEditStr') }}</div>
    </template>
    <el-form ref="dialogFormRef" :model="dialogForm" label-position="top" class="form-readonly" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item :label="$t('pageStr.ifaceNameStr')+' : '+infoData.toUpperCase()"></el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('pageStr.protocolStr')" prop="proto">
            <el-radio-group v-model="dialogForm.staticProtoInfo.proto" fill="#C29B74" @change="radioChange">
              <el-radio-button label="static">{{ $t('staticAddress') }}</el-radio-button>
              <el-radio-button label="dhcp">{{ $t('DHCPClient') }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <template v-if="dialogForm.staticProtoInfo.proto == 'static'">
          <el-col :span="6">
            <el-form-item :label="$t('pageStr.ipAddr2Str')" prop="staticProtoInfo.ipaddr">
              <el-input v-model="dialogForm.staticProtoInfo.ipaddr"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('pageStr.subMaskStr')" prop="netmask">
              <el-input v-model="dialogForm.staticProtoInfo.netmask"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('pageStr.gatewayStr')" prop="gateway">
              <el-input v-model="dialogForm.staticProtoInfo.gateway"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('pageStr.useDnsServerStr')" prop="dns">
              <el-input v-model="dialogForm.staticProtoInfo.dns"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-for="item of dialogForm.muiltIp.length">
            <el-form-item :label="$t('pageStr.ifaceAliasStr')+'_'+item">
              <el-input v-model="dialogForm.muiltIp[item - 1]" :maxlength="15">
                <template #suffix>
                  <el-icon v-if="dialogForm.muiltIp.length > 1" color="#E06363" :size="20" style="cursor: pointer"
                           @click="delIpRow(item)">
                    <CloseBold/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button v-if="dialogForm.muiltIp.length < 8" style="width: 100%;margin-top: 30px; margin-bottom: 18px"
                       @click="addIp">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-button>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <template #footer>
      <div style="display: flex; justify-content: space-between">
        <div style="display: flex">
          <img style="width: 18px; height: 18px;" src="/icon/tipIcon.png">
          <div style="font-size: 14px">{{ $t('pageStr.takeNetworkEffectAfterRebootStr') }}</div>
        </div>
        <div>
          <el-button style="width: 110px;" type="primary" :loading="saveLoading"
                     @click="handleSubmit(dialogFormRef)">{{ $t('tabsStr.applyStr') }}
          </el-button>
          <el-button class="default-btn" @click="visible = false">{{ $t('pageStr.cancelStr') }}
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="PortDialog">
import {reactive, ref, onBeforeMount, defineEmits, defineProps, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {reqGetIfaceDetailByName, reqReset, reqSetIface} from '@/api/network/interface'
import {validateIP} from "@/utils";
import {useI18n} from 'vue-i18n'

const {t} = useI18n()
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  infoData: {
    type: String,
    default: ''
  }
})
const dialogFormRef = ref(null)
const dialogForm = ref({
  muiltIp: [''],
  staticProtoInfo: {
    proto: "static"
  }
})

function radioChange(val) {
  console.log('单选变化', val)
}

function addIp() {
  if (dialogForm.value.muiltIp.length > 7) {
    ElMessage.warning('最大支持8个IP')
    return
  }
  dialogForm.value.muiltIp.push('')
}

function delIpRow(rowId) {
  dialogForm.value.muiltIp.splice(rowId - 1, 1)
}

onBeforeMount(() => {
  console.log('add框初始化', props.infoData)
  reqGetIfaceDetailByName(props.infoData).then((res) => {
    console.log('对话框详情', res)
    dialogForm.value = {
      muiltIp: res.aliasip.length ? res.aliasip : [''],
      staticProtoInfo: res.staticProtoInfo
    }
  })
})

const detail = ref({})
const saveLoading = ref(false)
const visible = ref(true)
const emits = defineEmits(['update:modelValue', 'success'])
const rules = reactive({
  'staticProtoInfo.ipaddr': [
    {required: true, message: '必填项不能为空', trigger: 'blur'},
    {validator: validateIP, message: '请输入正确的IP', trigger: 'change'}],
})


/**
 * 关闭对话框的回调函数
 */
function closed() {
  emits('update:modelValue', false)
}


// 提交
function handleSubmit(formEl) {
  formEl?.validate(async (valid) => {
    if (!valid) {
      return
    }
    const submitForm = {
      netName: props.infoData,
      proto: dialogForm.value.staticProtoInfo.proto,
      ipaddr: dialogForm.value.staticProtoInfo.ipaddr,
      netmask: dialogForm.value.staticProtoInfo.netmask,
      gateway: dialogForm.value.staticProtoInfo.gateway,
      dns: dialogForm.value.staticProtoInfo.dns,
    }
    let i = 0
    dialogForm.value.muiltIp.forEach((item) => {
      submitForm['ipaddr' + i] = item
      i++
    })
    submitForm.num = i
    console.log('新增数据，', submitForm)
    saveLoading.value = true
    _add(submitForm)
  })
}

async function _add(data) {
  try {
    await reqSetIface(data)
    // 修改IP成功后 重启网络模块
    await reqReset()
    onSuccess()
  } catch (err) {
    ElMessage.error(t('errorTip'))
  }
  saveLoading.value = false
}

function onSuccess() {
  ElMessage.success(t('successTip'))
  visible.value = false
  emits('success')
}
</script>

<style scoped>
.dialog-title {
  width: 100%;
  margin-left: -20px;
  margin-top: -20px;
  font-size: 18px;
  color: #161940;
  font-family: 'Microsoft YaHei';
  line-height: 50px;
  height: 50px;
  padding-left: 30px;
  background: linear-gradient(90deg, rgba(245, 233, 220, 0.8) 0%, rgba(245, 233, 220, 0.2) 100%);
  border-radius: 8px 8px 0px 0px;
  opacity: 1;
}
</style>
